<template>
  <div>
    <n-modal
      :show="props.showModal"
      :on-mask-click="maskClick"
      :class="{ 'blow-up': isBlowUp }"
    >
      <n-card
        style="width: 50%; max-height: 60vh; min-width: 650px"
        :title="props.dialogTitle"
        :bordered="false"
        size="huge"
        role="dialog"
        aria-modal="true"
        header-style="padding:20px;padding-bottom:10px;"
        content-style="overflow: hidden; overflow-y: auto;padding:20px;padding-top:0px;"
      >
        <template #header-extra>
          <n-button @click="closeModal" text size="tiny" color="#ff69b4">
            <template #icon>
              <n-icon size="20">
                <Close></Close>
              </n-icon>
            </template>
          </n-button>
        </template>
        <div style="margin: 20px 0px" v-if="props.dialogType == 1">
          <n-form
            label-placement="left"
            ref="formRef"
            :label-width="80"
            :model="formValue"
            :rules="rules"
            :size="size"
          >
            <n-form-item label="碎片描述" path="shard">
              <n-input v-model:value="formValue.shard" placeholder="请输入描述" />
            </n-form-item>
            <n-form-item label="碎片所属" path="tag">
              <n-cascader
                v-model:value="formValue.tag"
                placeholder="碎片所属"
                :options="options"
                check-strategy="all"
                size="medium"
                clearable="true"
                :show-path="true"
                :expand-trigger="hover"
                :filterable="true"
              />
            </n-form-item>
            <n-form-item label="是否公开">
              <n-switch v-model:value="formValue.active" size="medium">
                <template #checked> 公开的 </template>
                <template #unchecked>私密的 </template>
                <template #checked-icon>
                  <n-icon :component="EyeOutline" />
                </template>
                <template #unchecked-icon>
                  <n-icon :component="EyeOffOutline" />
                </template>
              </n-switch>
            </n-form-item>
            <n-form-item label="上传碎片" path="previewFileList">
              <n-upload
                v-if="!isUpdate"
                v-model:file-list="formValue.previewFileList"
                v-model:value="formValue.previewFileList"
                accept="image/png, image/jpeg"
                list-type="image-card"
                @preview="handlePreview"
                :max="1"
                :default-upload="false"
                :show-file-list="true"
                ref="uploadRef"
                :on-before-upload="handleBeforeRead"
              />
              <n-image v-else width="100" :src="formValue.previewFileList" />
            </n-form-item>
          </n-form>
        </div>
        <div v-else-if="props.dialogType == 2">
          <div v-if="!isInitialize">
            <n-form
              label-placement="left"
              ref="formPasswordRef"
              :label-width="80"
              :model="formPasswordValue"
              :rules="rulesPassword"
              :size="size"
            >
              <n-form-item label="原始密码" path="oldPassword">
                <n-input
                  v-model:value="formPasswordValue.oldPassword"
                  placeholder="请输入原始密码"
                />
              </n-form-item>
              <n-form-item label="新密码" path="newPassword">
                <n-input
                  v-model:value="formPasswordValue.newPassword"
                  placeholder="请输入新密码"
                />
              </n-form-item>
              <n-form-item label="确认密码" path="verifyNewPassword">
                <n-input
                  v-model:value="formPasswordValue.verifyNewPassword"
                  placeholder="请确认密码"
                />
              </n-form-item>
            </n-form>
          </div>

          <div v-else>
            <n-form
              label-placement="left"
              ref="formNewPasswordRef"
              :label-width="80"
              :model="formNewPasswordValue"
              :rules="rulesNewPassword"
              :size="size"
            >
              <n-form-item label="登录密码" path="adminPassword">
                <n-input
                  v-model:value="formNewPasswordValue.adminPassword"
                  placeholder="请输入登录密码"
                />
              </n-form-item>
            </n-form>
          </div>
        </div>
        <template #action>
          <div style="margin: -15px; display: flex; justify-content: flex-end; gap: 10px">
            <n-button size="small" @click="closeModal">取消</n-button>
            <n-button size="small" type="primary" @click="handleValidateClick">
              {{ isUpdate ? "立即更新" : "确定" }}
            </n-button>
            <n-button
              size="small"
              type="primary"
              color="#d01464"
              @click="initializeClick"
              v-if="props.dialogType == 2"
            >
              {{ !isInitialize ? "初始化密码" : "确定初始化" }}
            </n-button>
          </div>
        </template>
      </n-card>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { Close, EyeOutline, EyeOffOutline } from "@vicons/ionicons5";
import { addTag } from "@/api/tag.ts";
import { useStore } from "vuex";
import { ArchiveOutline as ArchiveIcon } from "@vicons/ionicons5";
import { uploadImage, updateImage } from "@/api/loveDiary.ts";

const props = defineProps({
  showModal: {
    type: Boolean,
    default: () => false,
  },
  data: {
    type: Array,
    default: "",
  },
  dialogType: {
    type: Number,
    default: () => 1,
  },
  dialogTitle: {
    type: String,
    default: () => "新增生活碎片",
  },
});
const store = useStore();
const formRef: any = ref(null);
const formPasswordRef = ref(null);
const formNewPasswordRef = ref(null);
const isInitialize = ref(false); //控制初始化私密密码的页面显示
const isBlowUp = ref(false);
const formValue: any = ref({
  shard: null,
  tag: null,
  previewFileList: [],
  active: true,
});
const rules = {
  shard: {
    required: true,
    trigger: ["blur", "input"],
    message: "请给碎片一个描述吧",
  },
  tag: {
    type: "string",
    required: true,
    trigger: ["blur", "change"],
    message: "碎片还没找到所属哦",
  },
  previewFileList: {
    type: "array",
    required: true,
    trigger: ["blur", "change"],
    message: "记得上传你们的瞬间",
  },
};
const formPasswordValue = ref({
  oldPassword: null,
  newPassword: null,
  verifyNewPassword: null,
});
const rulesPassword = {
  oldPassword: {
    required: true,
    trigger: ["blur", "input"],
    message: "请输入原始密码",
  },
  newPassword: {
    required: true,
    trigger: ["blur", "input"],
    message: "请输入新密码",
  },
  verifyNewPassword: {
    required: true,
    trigger: ["blur", "input"],
    message: "请确认新密码",
  },
};
const formNewPasswordValue = ref({
  adminPassword: null,
});
const rulesNewPassword = {
  adminPassword: {
    required: true,
    trigger: ["blur", "input"],
    message: "请输入登录密码",
  },
};
const options = ref();
const uploadRef = ref<any>(null);
const isUpdate = ref(false);
const imgData = ref();
const imgUrl = import.meta.env.VITE_APP_API_KEY;

const init = (row: any = null) => {
  isUpdate.value = false;
  options.value = [];
  console.log(props.data);
  props.data.forEach((d: any) => {
    options.value.push({
      label: d.t_name,
      value: d.t_id,
      children: getTreeChildren(d.children == undefined ? null : d.children),
    });
  });
  formValue.value.shard = null;
  formValue.value.tag = null;
  formValue.value.active = true;
  formValue.value.previewFileList = [];
  if (row != null) {
    isUpdate.value = true;
    console.log(row);
    formValue.value.shard = row.i_description;
    formValue.value.tag = row.i_tag;
    formValue.value.active = row.i_permissions == 1 ? true : false;
    formValue.value.previewFileList.push(imgUrl + row.i_filePath);
    imgData.value = row;
  }
};
const getTreeChildren = (data) => {
  if (data == undefined || data == null) {
    return;
  }
  let children: any = [];
  data.forEach((d: any) => {
    children.push({
      label: d.t_name,
      value: d.t_id,
      children: getTreeChildren(d.children),
    });
  });

  return children.length == 0 ? null : children;
};
const handleBeforeRead = async ({ file }: any) => {
  // 创建 FileReader 对象
  const reader: any = new FileReader();
  console.log(file);
  reader.onload = () => {
    const blobUrl = reader.result as string;
    // console.log(blobUrl);
    // 将读取结果转换为 Base64 格式并进行处理
    const base64Data = reader.result.split(",")[1]; // 获取 base64 数据部分
    // 进行后续处理，比如发送到服务器等
    formValue.value.previewFileList.push({
      id: file.id,
      name: file.name,
      status: "finished",
      url: blobUrl,
      data: file.file,
    });
    file.file.url = blobUrl;
  };

  // 读取文件并转换为 Data URL
  reader.readAsDataURL(file.file);
  // 你可以决定是否继续上传，返回true则继续，返回false则取消上传
  return false;
};

const maskClick = () => {
  isBlowUp.value = true;
  setTimeout(() => {
    isBlowUp.value = false;
  }, 500);
};
const initializeClick = () => {
  if (isInitialize.value) {
  } else {
    isInitialize.value = true;
  }
};
const emit = defineEmits(["closeModal", "getImage"]);

// 假设你有一个方法来切换模态框的显示状态
const closeModal = () => {
  emit("closeModal");
  isInitialize.value = false;
};
const handleValidateClick = (e) => {
  e.preventDefault();
  formRef.value?.validate((errors) => {
    if (!errors) {
      if (!isUpdate.value) {
        // 转换为KB
        const fileSizeKB = formValue.value.previewFileList[0].data.size / 1024;
        let pImg = {
          i_fileName: formValue.value.previewFileList[0].name.split(".")[0],
          i_uploader: store.state.userInfo?.u_Account ?? null,
          i_description: formValue.value.shard,
          i_size: fileSizeKB.toFixed(2),
          i_type: formValue.value.previewFileList[0].name.split(".")[1],
          i_tag: formValue.value.tag,
          i_permissions: formValue.value.active,
        };
        let formData = new FormData();
        formData.append("file", formValue.value.previewFileList[0].data);
        for (let key in pImg) {
          if (pImg.hasOwnProperty(key)) {
            if (pImg[key] != null) formData.append(key, pImg[key]);
          }
        }
        uploadImage(formData).then((res) => {
          console.log(res);
          if (res.code == 200) {
            window.$message.success(res.message);
            emit("getImage");
            formValue.value.shard = null;
            formValue.value.tag = null;
            formValue.value.active = true;
            formValue.value.previewFileList = [];
            closeModal();
          } else {
            window.$message.error(res.message);
          }
        });
      } else {
        imgData.value.i_description = formValue.value.shard;
        imgData.value.i_tag = formValue.value.tag;
        imgData.value.i_permissions = formValue.value.active ? 1 : -1;
        updateImage(imgData.value).then((res) => {
          if (res.code == 200) {
            window.$message.success(res.message);
            emit("getImage");
            closeModal();
          } else {
            window.$message.error(res.message);
          }
        });
      }
    } else {
      console.log(formValue.value);
      window.$message.error("表单验证错误");
    }
  });
};
defineExpose({ init });
</script>

<style scoped>
.blow-up {
  animation: scaleAnimation 0.5s infinite;
  transform-origin: center center;
  /* 设置缩放中心为元素中心点 */
}

@keyframes scaleAnimation {
  0% {
    transform: scale(1);
    transform-origin: center center;
  }

  50% {
    transform: scale(1.1);
    /* 在动画中点缩放到1.1倍 */
    transform-origin: center center;
  }

  100% {
    transform: scale(1);
    /* 在动画结束时缩放回原始大小 */
    transform-origin: center center;
  }
}
</style>
